package com.ktjy.t382.bank.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjy.t382.bank.entity.Account;
import com.ktjy.t382.bank.entity.Bank;
import com.ktjy.t382.bank.mapper.AccountMapper;
import com.ktjy.t382.bank.mapper.BankMapper;
import com.ktjy.t382.bank.service.BankService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BankServiceImpl implements BankService {
    @Resource
    BankMapper bankMapper;
    @Resource
    AccountMapper accountMapper;

    @Override
    public Account login(Account account) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cardno", account.getCardno());
        queryWrapper.eq("password", account.getPassword());
        return accountMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Bank> findPageVo(Bank bank, String cardno, String startTime, String endTime, Integer pageNo, Integer pageSize) {
        Page<Bank> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Bank> queryWrapper = new QueryWrapper<>();
        try {
            queryWrapper.eq("cardno", cardno)
                    .between("transactionDate", startTime, endTime)  // 修改为实体类中的字段名
                    .orderByDesc("transactionDate");

            return bankMapper.selectPage(page, queryWrapper).getRecords();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询交易记录失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> transfer(String fromCardno, String toCardno, double amount, String remark) {
        Map<String, Object> rest = new HashMap<>();

        // 基本验证
        if (amount <= 0 || fromCardno.equals(toCardno)) {
            rest.put("success", false);
            rest.put("message", amount <= 0 ? "转账金额必须大于零" : "不可向自己转账");
            return rest;
        }

        // 查询转出账户
        Account fromAccount = accountMapper.selectOne(new QueryWrapper<Account>().eq("cardno", fromCardno));
        if (fromAccount == null || fromAccount.getBalance() < amount) {
            rest.put("success", false);
            rest.put("message", fromAccount == null ? "转出账户不存在" : "余额不足");
            return rest;
        }

        // 查询转入账户
        Account toAccount = accountMapper.selectOne(new QueryWrapper<Account>().eq("cardno", toCardno));
        if (toAccount == null) {
            rest.put("success", false);
            rest.put("message", "没有该账户");
            return rest;
        }

        try {
            Date now = new Date();
            // 更新转出账户余额
            UpdateWrapper<Account> fromUpdate = new UpdateWrapper<>();
            fromUpdate.eq("cardno", fromCardno)
                    .setSql("balance = balance - " + amount);
            accountMapper.update(null, fromUpdate);

            // 更新转入账户余额
            UpdateWrapper<Account> toUpdate = new UpdateWrapper<>();
            toUpdate.eq("cardno", toCardno)
                    .setSql("balance = balance + " + amount);
            accountMapper.update(null, toUpdate);

            // 处理备注信息
            String fromRemark = remark == null || remark.trim().isEmpty() ?
                    "转给" + toCardno + "的转账" : remark;
            String toRemark = "来自" + fromCardno + "的转账";

            // 记录转出方交易
            Bank outRecord = new Bank();
            outRecord.setCardno(fromCardno);
            outRecord.setTransactionDate(now);
            outRecord.setAmount(amount);
            outRecord.setBalance(fromAccount.getBalance() - amount);
            outRecord.setTransactionType("转出");
            outRecord.setRemark(fromRemark);

            bankMapper.insert(outRecord);

            // 记录转入方交易
            Bank inRecord = new Bank();
            inRecord.setCardno(toCardno);
            inRecord.setTransactionDate(now);
            inRecord.setAmount(amount);
            inRecord.setBalance(toAccount.getBalance() + amount);
            inRecord.setTransactionType("转入");
            inRecord.setRemark(toRemark);

            bankMapper.insert(inRecord);

            rest.put("success", true);
            rest.put("message", "转账成功");
        } catch (Exception e) {
            throw new RuntimeException("转账失败", e);
        }

        return rest;
    }

    @Override
    public Account checkBalance(String cardno) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cardno", cardno);
        return accountMapper.selectOne(queryWrapper);
    }

    @Override
    public int confirmPassword(Account account) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cardno", account.getCardno());
        queryWrapper.eq("password", account.getPassword());
        return Math.toIntExact(accountMapper.selectCount(queryWrapper));
    }

    @Override
    public int changePassword(Account account) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cardno", account.getCardno());

        // Create update wrapper with new password
        Account updateAccount = new Account();
        updateAccount.setPassword(account.getPassword());

        return accountMapper.update(updateAccount, queryWrapper);
    }
}
